﻿using Microsoft.VisualBasic;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Reflection.Metadata;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Runtime.InteropServices.JavaScript.JSType;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.TreeView;
using Serilog;
using Serilog.Extensions.Logging;
using Serilog.Events;
using Serilog.Sinks.SystemConsole;
using SIPSorcery.SIP;
using SIPSorcery.SIP.App;
using SIPSorcery.Media;
using SIPSorcery.Net;
using SIPSorceryMedia.Abstractions;
using SIPSorceryMedia.Windows;
using System.Runtime.Intrinsics.Arm;

namespace Phone
{
    #region 结构体定义
    //GPS坐标结构体
    public struct GPS
    {
        public double jd;
        public double wd;
        public double hb;
    }

    //地址结构体
    public struct Address
    {
        public GPS gps;
        public string address;
    }
    #endregion

    //定义常量
    public static class Defines
    {
        public const int SIGNAL_DICT_VERSION = 1;
        public const int MAX_SIGNAL_DICT_COUNT = 10;
        public const int MAX_CUSTOM_SIGNAL_COUNT = 3;
        public const int MAX_ADDRESS_COUNT = 5;
        public const string RECEIVE_MSG_NUMBER_110 = "12110";
        public const string RECEIVE_MSG_NUMBER_119 = "12119";
        public const string RECEIVE_MSG_NUMBER_120 = "120";
        public const string RECEIVE_MSG_NUMBER_122 = "12122";
    }

    //定义全局变量
    public static class Vars
    {
        #region 全局变量
        public static int[] settings = new int[2];      //0:是否启用报警辅助功能,1:是否默认发送GPS
        public static GPS gps;
        public static Address[] address = new Address[Defines.MAX_ADDRESS_COUNT];   //自定义地址信息
        public static int address_count;
        public static string[,] signal_dict = new string[5, Defines.MAX_SIGNAL_DICT_COUNT];     //信号字典
        public static int signal_dict_version;
        public static string[] custom_signal = new string[Defines.MAX_CUSTOM_SIGNAL_COUNT];     //自定义信号
        public static int custom_signal_count;

        public static string sipUser = "";
        public static string sipPassword = "";
        public static string sipServerUri = "";
        public static string sipProxyUri = "";
        public static int expiry = 120;
        public static string sipSignUpUrl = "";
        public static string pstnUser1 = "";
        public static string pstnUser2 = "";

        public static SIP? sip;
        public static SIP? pstn1;
        public static SIP? pstn2;
        public static string busy_sip_or_pstn = "";
        public static string message = "";      //报警辅助信息
        public static string chatMessage = "";  //聊天信息
        public static string tag = "";          //报警辅助标签
        public static string localTag = "";     //本地标签

        public static Test? test;      // Test窗体,用于执行UI切换
        #endregion

        //初始化全局变量
        public static void Init()
        {
            test = Application.OpenForms.OfType<Test>().FirstOrDefault();

            // 全局变量设置默认值,然后读取配置文件
            settings[0] = 0;
            settings[1] = 0;
            gps.jd = -200;
            gps.wd = -200;
            gps.hb = -200;
            init_address();
            init_signal();
            ReadConfig();

            // 初始化SIP
            if (sipUser != "" && sipServerUri != "")
            {
                sip = new SIP();
                sip.StartUp(sipUser, sipPassword, sipServerUri, sipProxyUri, expiry, sipSignUpUrl);
                sip.Register();
                sip.OnRegisterSuccessEvent += () =>
                {
                    if (!sip.isListen)
                    {
                        Thread thread = new Thread(new ThreadStart(() => { sip.Listen(); }));
                        thread.IsBackground = true;
                        thread.Start();
                    }
                    if (!sip.isReceiveMsg)
                    {
                        Thread thread2 = new Thread(new ThreadStart(() => { sip.ReceiveMsg(); }));
                        thread2.IsBackground = true;
                        thread2.Start();
                    }
                };
            }

            if (pstnUser1 != "")
            {
                pstn1 = new SIP();
                pstn1.StartUp(pstnUser1, "", "127.0.0.1:5060;transport=udp");
                pstn1.Register();
                pstn1.OnRegisterSuccessEvent += () =>
                {
                    if (!pstn1.isListen)
                    {
                        Thread thread = new Thread(new ThreadStart(() => { pstn1.Listen(); }));
                        thread.IsBackground = true;
                        thread.Start();
                    }
                    if (!pstn1.isReceiveMsg)
                    {
                        Thread thread2 = new Thread(new ThreadStart(() => { pstn1.ReceiveMsg(); }));
                        thread2.IsBackground = true;
                        thread2.Start();
                    }
                };
            }

            if (pstnUser2 != "")
            {
                pstn2 = new SIP();
                pstn2.StartUp(pstnUser2, "", "127.0.0.1:5060;transport=udp");
                pstn2.Register();
                pstn2.OnRegisterSuccessEvent += () =>
                {
                    if (!pstn2.isListen)
                    {
                        Thread thread = new Thread(new ThreadStart(() => { pstn2.Listen(); }));
                        thread.IsBackground = true;
                        thread.Start();
                    }
                    if (!pstn2.isReceiveMsg)
                    {
                        Thread thread2 = new Thread(new ThreadStart(() => { pstn2.ReceiveMsg(); }));
                        thread2.IsBackground = true;
                        thread2.Start();
                    }
                };
            }

            // 添加事件处理函数
            AddEventHandler();
        }

        #region 初始化函数


        public static void init_address()
        {
            address_count = 0;
            for (int i = 0; i < Defines.MAX_ADDRESS_COUNT; i++)
            {
                address[i].gps.jd = -200;
                address[i].gps.wd = -200;
                address[i].gps.hb = -200;
                address[i].address = "";
            }
        }

        public static void init_signal()
        {
            //自定义信号初始化
            custom_signal_count = 0;
            for (int i = 0; i < Defines.MAX_CUSTOM_SIGNAL_COUNT; i++)
            {
                custom_signal[i] = "";
            }
            //信号字典初始化
            for (int i = 0; i < 5; i++)
            {
                for (int j = 0; j < Defines.MAX_SIGNAL_DICT_COUNT; j++)
                {
                    signal_dict[i, j] = "";
                }
            }
            signal_dict_version = Defines.SIGNAL_DICT_VERSION;
            signal_dict[0, 0] = "发送GPS定位";
            signal_dict[1, 0] = "紧急求助";
            signal_dict[1, 1] = "我不方便说话";
            signal_dict[1, 2] = "帮我叫救护车";
            signal_dict[1, 3] = "枪击事件";
            signal_dict[1, 4] = "持刀伤人事件";
            signal_dict[1, 5] = "有人跳楼";
            signal_dict[2, 0] = "火灾报警";
            signal_dict[2, 1] = "水泥塌方";
            signal_dict[2, 2] = "帮我叫救护车";
            signal_dict[2, 3] = "需要液压钳";
            signal_dict[3, 0] = "需要救护车";
            signal_dict[3, 1] = "我需要救援";
            signal_dict[3, 2] = "我周围一人需要救援";
            signal_dict[3, 3] = "我周围多人需要救援";
            signal_dict[3, 4] = "受伤大出血";
            signal_dict[3, 5] = "中毒昏迷";
            signal_dict[4, 0] = "发生车祸";
            signal_dict[4, 1] = "帮我叫救护车";
            signal_dict[4, 2] = "车辆起火";
            signal_dict[4, 3] = "车辆坠落";
        }

        public static void ReadConfig()
        {
            string path = Application.StartupPath + "\\config.txt";
            string[] lines = System.IO.File.ReadAllLines(path);
            for (int i = 0; i < lines.Length; i++)
            {
                string[] items = lines[i].Split('=');
                switch (items[0])
                {
                    case "sipUser":
                        sipUser = items[1];
                        break;
                    case "sipPassword":
                        sipPassword = items[1];
                        break;
                    case "sipServerUri":
                        sipServerUri = lines[i].Substring("sipServerUri=".Length);
                        break;
                    case "sipProxyUri":
                        sipProxyUri = lines[i].Substring("sipProxyUri=".Length);
                        break;
                    case "expiry":
                        expiry = int.Parse(items[1]);
                        break;
                    case "sipSignUpUrl":
                        sipSignUpUrl = items[1];
                        break;
                    case "pstnUser1":
                        pstnUser1 = items[1];
                        break;
                    case "pstnUser2":
                        pstnUser2 = items[1];
                        break;
                    case "settings[0]":
                        settings[0] = int.Parse(items[1]);
                        break;
                    case "settings[1]":
                        settings[1] = int.Parse(items[1]);
                        break;
                    case "gps":
                        string[] gps_items = items[1].Split(';');
                        gps.jd = double.Parse(gps_items[0]);
                        gps.wd = double.Parse(gps_items[1]);
                        gps.hb = double.Parse(gps_items[2]);
                        break;
                    case "address_count":
                        address_count = int.Parse(items[1]);
                        break;
                    case "custom_signal_count":
                        custom_signal_count = int.Parse(items[1]);
                        break;
                    default:
                        break;
                }
                if (items[0].StartsWith("address["))
                {
                    int index = int.Parse(items[0].Substring(8, items[0].Length - 9));
                    string[] address_items = items[1].Split(';');
                    address[index].gps.jd = double.Parse(address_items[0]);
                    address[index].gps.wd = double.Parse(address_items[1]);
                    address[index].gps.hb = double.Parse(address_items[2]);
                    address[index].address = address_items[3];
                }
                if (items[0].StartsWith("custom_signal["))
                {
                    int index = int.Parse(items[0].Substring(14, items[0].Length - 15));
                    custom_signal[index] = items[1];
                }
            }
        }

        public static void AddEventHandler()
        {
            // 呼叫事件处理函数
            if (sip != null) sip.OnActiveInviteEvent += () =>
            {
                busy_sip_or_pstn = "sip";
                chatMessage = "";
                tag = "";
                pstn1?.SetRemoteUser(sip.GetRemoteUser());
                pstn2?.SetRemoteUser(sip.GetRemoteUser());
                test?.Invoke(new Action(() =>
                {
                    Calling calling = new Calling();
                    calling.Show();
                    calling.Location = Application.OpenForms[Application.OpenForms.Count - 2].Location;
                    Application.OpenForms[Application.OpenForms.Count - 2].Hide();
                }));
            };
            if (pstn1 != null) pstn1.OnActiveInviteEvent += () =>
            {
                busy_sip_or_pstn = "pstn1";
                chatMessage = "";
                tag = "";
                sip?.SetRemoteUser(pstn1.GetRemoteUser());
                pstn2?.SetRemoteUser(pstn1.GetRemoteUser());
                test?.Invoke(new Action(() =>
                {
                    Calling calling = new Calling();
                    calling.Show();
                    calling.Location = Application.OpenForms[Application.OpenForms.Count - 2].Location;
                    Application.OpenForms[Application.OpenForms.Count - 2].Hide();
                }));
            };
            if (pstn2 != null) pstn2.OnActiveInviteEvent += () =>
            {
                busy_sip_or_pstn = "pstn2";
                chatMessage = "";
                tag = "";
                sip?.SetRemoteUser(pstn2.GetRemoteUser());
                pstn1?.SetRemoteUser(pstn2.GetRemoteUser());
                test?.Invoke(new Action(() =>
                {
                    Calling calling = new Calling();
                    calling.Show();
                    calling.Location = Application.OpenForms[Application.OpenForms.Count - 2].Location;
                    Application.OpenForms[Application.OpenForms.Count - 2].Hide();
                }));
            };

            // 对方振铃
            if (sip != null) sip.OnActiveRingingEvent += () =>
            {
                Calling calling = Application.OpenForms.OfType<Calling>().FirstOrDefault();
                if (calling != null)
                {
                    calling.ring();
                }
            };
            if (pstn1 != null) pstn1.OnActiveRingingEvent += () =>
            {
                Calling calling = Application.OpenForms.OfType<Calling>().FirstOrDefault();
                if (calling != null)
                {
                    calling.ring();
                }
            };
            if (pstn2 != null) pstn2.OnActiveRingingEvent += () =>
            {
                Calling calling = Application.OpenForms.OfType<Calling>().FirstOrDefault();
                if (calling != null)
                {
                    calling.ring();
                }
            };

            // 对方忙线
            if (sip != null) sip.OnActiveBusyEvent += () =>
            {
                Calling calling = Application.OpenForms.OfType<Calling>().FirstOrDefault();
                if (calling != null)
                {
                    calling.busy();
                }
            };
            if (pstn1 != null) pstn1.OnActiveBusyEvent += () =>
            {
                Calling calling = Application.OpenForms.OfType<Calling>().FirstOrDefault();
                if (calling != null)
                {
                    calling.busy();
                }
            };
            if (pstn2 != null) pstn2.OnActiveBusyEvent += () =>
            {
                Calling calling = Application.OpenForms.OfType<Calling>().FirstOrDefault();
                if (calling != null)
                {
                    calling.busy();
                }
            };

            // 对方拒接
            if (sip != null) sip.OnActiveDeclineEvent += () =>
            {
                Calling calling = Application.OpenForms.OfType<Calling>().FirstOrDefault();
                if (calling != null)
                {
                    calling.decline();
                }
            };
            if (pstn1 != null) pstn1.OnActiveDeclineEvent += () =>
            {
                Calling calling = Application.OpenForms.OfType<Calling>().FirstOrDefault();
                if (calling != null)
                {
                    calling.decline();
                }
            };
            if (pstn2 != null) pstn2.OnActiveDeclineEvent += () =>
            {
                Calling calling = Application.OpenForms.OfType<Calling>().FirstOrDefault();
                if (calling != null)
                {
                    calling.decline();
                }
            };

            // End事件
            if (sip != null) sip.OnEndEvent += () =>
            {
                busy_sip_or_pstn = "";
                message = "";
                chatMessage = "";
                tag = "";
                localTag = "";
                pstn1?.SetRemoteUser("");
                pstn2?.SetRemoteUser("");

                try
                {
                    test?.Invoke(new Action(() =>
                    {
                        if (Application.OpenForms.OfType<Text>().FirstOrDefault() != null)
                        {
                            Application.OpenForms[Application.OpenForms.Count - 2].Show();
                            Application.OpenForms[Application.OpenForms.Count - 2].Location = Application.OpenForms[Application.OpenForms.Count - 1].Location;
                            Application.OpenForms[Application.OpenForms.Count - 1].Close();
                        }
                        Application.OpenForms[Application.OpenForms.Count - 2].Show();
                        Application.OpenForms[Application.OpenForms.Count - 2].Location = Application.OpenForms[Application.OpenForms.Count - 1].Location;
                        Application.OpenForms[Application.OpenForms.Count - 1].Close();
                    }));
                }
                catch (Exception ex)
                {

                }
            };
            if (pstn1 != null) pstn1.OnEndEvent += () =>
            {
                busy_sip_or_pstn = "";
                message = "";
                chatMessage = "";
                tag = "";
                sip?.SetRemoteUser("");
                pstn2?.SetRemoteUser("");
                try
                {
                    test?.Invoke(new Action(() =>
                    {

                        if (Application.OpenForms.OfType<Text>().FirstOrDefault() != null)
                        {
                            Application.OpenForms[Application.OpenForms.Count - 2].Show();
                            Application.OpenForms[Application.OpenForms.Count - 2].Location = Application.OpenForms[Application.OpenForms.Count - 1].Location;
                            Application.OpenForms[Application.OpenForms.Count - 1].Close();
                        }
                        Application.OpenForms[Application.OpenForms.Count - 2].Show();
                        Application.OpenForms[Application.OpenForms.Count - 2].Location = Application.OpenForms[Application.OpenForms.Count - 1].Location;
                        Application.OpenForms[Application.OpenForms.Count - 1].Close();

                    }));
                }
                catch (Exception ex)
                {

                }
            };
            if (pstn2 != null) pstn2.OnEndEvent += () =>
            {
                busy_sip_or_pstn = "";
                message = "";
                chatMessage = "";
                tag = "";
                sip?.SetRemoteUser("");
                pstn1?.SetRemoteUser("");
                try
                {
                    test?.Invoke(new Action(() =>
                    {

                        if (Application.OpenForms.OfType<Text>().FirstOrDefault() != null)
                        {
                            Application.OpenForms[Application.OpenForms.Count - 2].Show();
                            Application.OpenForms[Application.OpenForms.Count - 2].Location = Application.OpenForms[Application.OpenForms.Count - 1].Location;
                            Application.OpenForms[Application.OpenForms.Count - 1].Close();
                        }
                        Application.OpenForms[Application.OpenForms.Count - 2].Show();
                        Application.OpenForms[Application.OpenForms.Count - 2].Location = Application.OpenForms[Application.OpenForms.Count - 1].Location;
                        Application.OpenForms[Application.OpenForms.Count - 1].Close();

                    }));
                }
                catch (Exception ex)
                {

                }
            };

            // 对方接通事件
            if (sip != null) sip.OnActiveTalkingEvent += () =>
            {
                test?.Invoke(new Action(() =>
                {
                    Talking talking = new Talking();
                    talking.Show();
                    talking.Location = Application.OpenForms.OfType<Calling>().FirstOrDefault().Location;
                    Application.OpenForms.OfType<Calling>().FirstOrDefault().Close();
                }));
            };
            if (pstn1 != null) pstn1.OnActiveTalkingEvent += () =>
            {
                test?.Invoke(new Action(() =>
                {
                    Talking talking = new Talking();
                    talking.Show();
                    talking.Location = Application.OpenForms.OfType<Calling>().FirstOrDefault().Location;
                    Application.OpenForms.OfType<Calling>().FirstOrDefault().Close();
                }));
            };
            if (pstn2 != null) pstn2.OnActiveTalkingEvent += () =>
            {
                test?.Invoke(new Action(() =>
                {
                    Talking talking = new Talking();
                    talking.Show();
                    talking.Location = Application.OpenForms.OfType<Calling>().FirstOrDefault().Location;
                    Application.OpenForms.OfType<Calling>().FirstOrDefault().Close();
                }));
            };

            // 收到消息事件
            if (sip != null) sip.OnReceiveMsgEvent += (message) =>
            {
                if (message.Body.Contains(localTag))
                {
                    if (message.Body.Contains("Tag="))
                    {
                        tag = message.Body.Split("Tag=")[1].Split(';')[0];
                        string remoteMessageNumber = "";
                        switch (sip.GetRemoteUser())
                        {
                            case "110":
                                remoteMessageNumber = Defines.RECEIVE_MSG_NUMBER_110;
                                break;
                            case "119":
                                remoteMessageNumber = Defines.RECEIVE_MSG_NUMBER_119;
                                break;
                            case "120":
                                remoteMessageNumber = Defines.RECEIVE_MSG_NUMBER_120;
                                break;
                            case "122":
                                remoteMessageNumber = Defines.RECEIVE_MSG_NUMBER_122;
                                break;
                        }
                        pstn1?.SendMsg(remoteMessageNumber, "flag:Tag=" + tag + ";Number=" + pstnUser1 + ";");
                        pstn2?.SendMsg(remoteMessageNumber, "flag:Tag=" + tag + ";Number=" + pstnUser2 + ";");
                    }
                }
                else if (message.Body.Contains("Chat=") && message.Body.Contains("Tag=") && message.Body.Split("Tag=")[1].Split(';')[0] == tag)
                {
                    chatMessage += "对方：" + message.Body.Split("Chat=")[1].Split(";")[0]+"\n";
                    Text text = Application.OpenForms.OfType<Text>().FirstOrDefault();
                    if (text != null)
                    {
                        text.AddMessage("对方:" + message.Body.Split("Chat=")[1].Split(";")[0]+"\n");
                    }
                }
            };
            if (pstn1 != null) pstn1.OnReceiveMsgEvent += (message) =>
            {
                if (message.Body.Contains(localTag))
                {
                    if (message.Body.Contains("Tag="))
                    {
                        tag = message.Body.Split("Tag=")[1].Split(';')[0];
                        string remoteMessageNumber = "";
                        switch (sip.GetRemoteUser())
                        {
                            case "110":
                                remoteMessageNumber = Defines.RECEIVE_MSG_NUMBER_110;
                                break;
                            case "119":
                                remoteMessageNumber = Defines.RECEIVE_MSG_NUMBER_119;
                                break;
                            case "120":
                                remoteMessageNumber = Defines.RECEIVE_MSG_NUMBER_120;
                                break;
                            case "122":
                                remoteMessageNumber = Defines.RECEIVE_MSG_NUMBER_122;
                                break;
                        }
                        sip?.SendMsg(remoteMessageNumber, "flag:Tag=" + tag + ";Number=" + sipUser+";");
                        pstn2?.SendMsg(remoteMessageNumber, "flag:Tag=" + tag + ";Number=" + pstnUser2+";");
                    }
                }
                else if (message.Body.Contains("Chat=") && message.Body.Contains("Tag=") && message.Body.Split("Tag=")[1].Split(';')[0] == tag)
                {
                    chatMessage += "对方：" + message.Body.Split("Chat=")[1].Split(";")[0]+"\n";
                    Text text = Application.OpenForms.OfType<Text>().FirstOrDefault();
                    if (text != null)
                    {
                        text.AddMessage("对方：" + message.Body.Split("Chat=")[1].Split(";")[0]+"\n");
                    }
                }
            };
            if (pstn2 != null) pstn2.OnReceiveMsgEvent += (message) =>
            {
                if (message.Body.Contains(localTag))
                {
                    if (message.Body.Contains("Tag="))
                    {
                        tag = message.Body.Split("Tag=")[1].Split(';')[0];
                        string remoteMessageNumber = "";
                        switch (sip.GetRemoteUser())
                        {
                            case "110":
                                remoteMessageNumber = Defines.RECEIVE_MSG_NUMBER_110;
                                break;
                            case "119":
                                remoteMessageNumber = Defines.RECEIVE_MSG_NUMBER_119;
                                break;
                            case "120":
                                remoteMessageNumber = Defines.RECEIVE_MSG_NUMBER_120;
                                break;
                            case "122":
                                remoteMessageNumber = Defines.RECEIVE_MSG_NUMBER_122;
                                break;
                        }
                        sip?.SendMsg(remoteMessageNumber, "flag:Tag=" + tag + ";Number=" + sipUser+";");
                        pstn1?.SendMsg(remoteMessageNumber, "flag:Tag=" + tag + ";Number=" + pstnUser1+";");
                    }
                }
                else if (message.Body.Contains("Chat=") && message.Body.Contains("Tag=") && message.Body.Split("Tag=")[1].Split(';')[0] == tag)
                {
                    chatMessage += "对方：" + message.Body.Split("Chat=")[1].Split(";")[0]+"\n";
                    Text text = Application.OpenForms.OfType<Text>().FirstOrDefault();
                    if (text != null)
                    {
                        text.AddMessage("对方：" + message.Body.Split("Chat=")[1].Split(";")[0]+"\n");
                    }
                }
            };

            // 收到呼叫事件
            if (sip != null) sip.OnPassiveRingingEvent += () =>
            {
                busy_sip_or_pstn = "sip";
                chatMessage = "";
                tag = "";
                pstn1?.SetRemoteUser(sip.GetRemoteUser());
                pstn2?.SetRemoteUser(sip.GetRemoteUser());
                test?.Invoke(new Action(() =>
                {
                    Ringing ringing = new Ringing();
                    ringing.Show();
                    ringing.Location = Application.OpenForms[Application.OpenForms.Count - 2].Location;
                    Application.OpenForms[Application.OpenForms.Count - 2].Hide();
                }));
            };
            if (pstn1 != null) pstn1.OnPassiveRingingEvent += () =>
            {
                busy_sip_or_pstn = "pstn1";
                chatMessage = "";
                tag = "";
                sip?.SetRemoteUser(pstn1.GetRemoteUser());
                pstn2?.SetRemoteUser(pstn1.GetRemoteUser());
                test?.Invoke(new Action(() =>
                {
                    Ringing ringing = new Ringing();
                    ringing.Show();
                    ringing.Location = Application.OpenForms[Application.OpenForms.Count - 2].Location;
                    Application.OpenForms[Application.OpenForms.Count - 2].Hide();
                }));
            };
            if (pstn2 != null) pstn2.OnPassiveRingingEvent += () =>
            {
                busy_sip_or_pstn = "pstn2";
                chatMessage = "";
                tag = "";
                sip?.SetRemoteUser(pstn2.GetRemoteUser());
                pstn1?.SetRemoteUser(pstn2.GetRemoteUser());
                test?.Invoke(new Action(() =>
                {
                    Ringing ringing = new Ringing();
                    ringing.Show();
                    ringing.Location = Application.OpenForms[Application.OpenForms.Count - 2].Location;
                    Application.OpenForms[Application.OpenForms.Count - 2].Hide();
                }));
            };

            // 被动成功建立通话事件
            if (sip != null) sip.OnPassiveTalkingEvent += () =>
            {
                test?.Invoke(new Action(() =>
                {
                    Talking talking = new Talking();
                    talking.Show();
                    talking.Location = Application.OpenForms.OfType<Ringing>().FirstOrDefault().Location;
                    Application.OpenForms.OfType<Ringing>().FirstOrDefault().Close();
                }));
            };
            if (pstn1 != null) pstn1.OnPassiveTalkingEvent += () =>
            {
                test?.Invoke(new Action(() =>
                {
                    Talking talking = new Talking();
                    talking.Show();
                    talking.Location = Application.OpenForms.OfType<Ringing>().FirstOrDefault().Location;
                    Application.OpenForms.OfType<Ringing>().FirstOrDefault().Close();
                }));
            };
            if (pstn2 != null) pstn2.OnPassiveTalkingEvent += () =>
            {
                test?.Invoke(new Action(() =>
                {
                    Talking talking = new Talking();
                    talking.Show();
                    talking.Location = Application.OpenForms.OfType<Ringing>().FirstOrDefault().Location;
                    Application.OpenForms.OfType<Ringing>().FirstOrDefault().Close();
                }));
            };
        }
        #endregion

        public static void CleanUp()
        {
            WriteConfig();
            Thread t1 = new Thread(new ThreadStart(() =>
            {
                sip?.CleanUp();

            }));
            Thread t2 = new Thread(new ThreadStart(() =>
            {
                pstn1?.CleanUp();
            }));
            Thread t3 = new Thread(new ThreadStart(() =>
            {
                pstn2?.CleanUp();
            }));
            t1.Start();
            t2.Start();
            t3.Start();
            t1.Join();
            t2.Join();
            t3.Join();
        }

        #region 全局变量写入配置文件函数
        public static void WriteConfig()
        {
            string path = Application.StartupPath + "\\config.txt";
            // 将设置逐行写入配置文件
            using (System.IO.StreamWriter file = new System.IO.StreamWriter(path, false))
            {
                file.WriteLine("sipUser=" + sipUser);
                file.WriteLine("sipPassword=" + sipPassword);
                file.WriteLine("sipServerUri=" + sipServerUri);
                file.WriteLine("sipProxyUri=" + sipProxyUri);
                file.WriteLine("expiry=" + expiry);
                file.WriteLine("sipSignUpUrl=" + sipSignUpUrl);
                file.WriteLine("pstnUser1=" + pstnUser1);
                file.WriteLine("pstnUser2=" + pstnUser2);
                file.WriteLine("settings[0]=" + settings[0]);
                file.WriteLine("settings[1]=" + settings[1]);
                file.WriteLine("gps=" + gps.jd + ";" + gps.wd + ";" + gps.hb);
                file.WriteLine("address_count=" + address_count);
                file.WriteLine("custom_signal_count=" + custom_signal_count);
                for (int i = 0; i < address_count; i++)
                {
                    file.WriteLine("address[" + i + "]=" + address[i].gps.jd + ";" + address[i].gps.wd + ";" + address[i].gps.hb + ";" + address[i].address);
                }
                for (int i = 0; i < custom_signal_count; i++)
                {
                    file.WriteLine("custom_signal[" + i + "]=" + custom_signal[i]);
                }
            }
        }
        #endregion

        public static void Call(string number, string message, string sip_or_pstn)
        {
            if (busy_sip_or_pstn != "")
            {
                MessageBox.Show("当前正在通话中，请稍后再试！");
                return;
            }
            localTag = Guid.NewGuid().ToString();
            switch (sip_or_pstn)
            {
                case "sip":
                    Thread thread = new Thread(new ThreadStart(() => { sip?.Call(number, message+"|LocalTag="+localTag); }));
                    thread.IsBackground = true;
                    thread.Start();
                    break;
                case "pstn1":
                    Thread thread1 = new Thread(new ThreadStart(() => { pstn1?.Call(number, message + "|LocalTag=" + localTag); }));
                    thread1.IsBackground = true;
                    thread1.Start();
                    break;
                case "pstn2":
                    Thread thread2 = new Thread(new ThreadStart(() => { pstn2?.Call(number, message + "|LocalTag=" + localTag); }));
                    thread2.IsBackground = true;
                    thread2.Start();
                    break;
            }
        }
    }
}
